package org.dllwh.milvus.v1;

import io.milvus.client.MilvusServiceClient;
import io.milvus.grpc.DescribeIndexResponse;
import io.milvus.param.IndexType;
import io.milvus.param.MetricType;
import io.milvus.param.R;
import io.milvus.param.RpcStatus;
import io.milvus.param.index.CreateIndexParam;
import io.milvus.param.index.DescribeIndexParam;
import lombok.extern.slf4j.Slf4j;
import org.dllwh.milvus.model.AjaxResult;
import org.dllwh.milvus.util.MilvusHelper;

/**
 * 把今天最好的表现当作明天最新的起点．．～
 * <p>
 * Today the best performance as tomorrow the newest starter!
 *
 * @ClassName MilvusIndexHelper
 * @Description Milvus V1 索引操作
 * @Author: <a href="mailto:duleilewuhen@sina.com">独泪了无痕</a>
 * @Date 2025-05-24 14:36
 * @版本 V 1.0.1
 * @since JDK 17
 */
@Slf4j
public class MilvusIndexHelper {
    /**
     * 创建集合索引 -- 加在向量字段上
     *
     * @param collectName 指定集合名称
     * @param fieldName
     * @param indexType
     * @param metricType
     * @param extraParam  JSON 字符串
     */
    public static AjaxResult createIndex(String collectName, String fieldName, IndexType indexType, MetricType metricType, String extraParam) {
        MilvusServiceClient milvusClient = MilvusConnectHelper.getMilvusServiceClient();
        CreateIndexParam.Builder createIndexParam = CreateIndexParam.newBuilder()
                .withCollectionName(collectName)
                .withFieldName(fieldName)
                .withIndexType(indexType)
                .withMetricType(metricType)
                .withExtraParam(extraParam)
                .withSyncMode(Boolean.FALSE);
        R<RpcStatus> response = milvusClient.createIndex(createIndexParam.build());
        if (response.getStatus() != R.Status.Success.getCode()) {
            log.error("创建集合（{}）索引失败，失败原因是:{}", collectName, response.getMessage());
        }
        return MilvusHelper.handleRpcStatus(collectName, "创建集合索引", response);
    }

    /**
     * @param collectName  指定集合名称
     * @param databaseName
     * @param fieldName
     * @return
     */
    public static boolean DescribeIndex(String collectName, String databaseName, String fieldName) {
        MilvusServiceClient milvusClient = MilvusConnectHelper.getMilvusServiceClient();
        DescribeIndexParam.Builder describeIndexParam = DescribeIndexParam.newBuilder()
                .withCollectionName(collectName)
                .withDatabaseName(databaseName)
                .withFieldName(fieldName);

        R<DescribeIndexResponse> response = milvusClient.describeIndex(describeIndexParam.build());
        if (response.getStatus() != R.Status.Success.getCode()) {
            log.error("获取集合（{}）索引失败，失败原因是:{}", collectName, response.getMessage());
            return false;
        }
        return true;
    }
}
